<template>
  <el-select
    v-model="selectValue"
    :clearable="clearable"
    :disabled="disabled"
    :multiple="multiple"
    :placeholder="placeholder"
    :readonly="readonly"
    @change="onChange"
  >
    <el-option v-for="item in list" :key="item.id" :label="item.dictLabel" :value="item.dictValue" />
  </el-select>
</template>
<script>
import { postRequest, getLocalStorage } from "@/api/mains";

export default defineComponent({
  name: "CommonSelect",
  props: {
    modelValue: {
      type: [Number, String, Array],
      default: ""
    },
    opitionList: {
      type: Array,
      default: () => []
    },
    dictUrl: {
      type: String,
      default: ""
    },
    clearable: {
      type: Boolean,
      default: true
    },
    dictCode: {
      type: String,
      default: ""
    },
    disabled: {
      type: Boolean,
      default: false
    },
    readonly: {
      type: Boolean,
      default: false
    },
    multiple: {
      type: Boolean,
      default: false
    },
    placeholder: {
      type: String,
      default: ""
    }
  },
  emits: {
    "update:model-value": null
  },

  setup(props, { emit }) {
    const list = ref([]);

    const selectValue = ref(props.modelValue);
    const getList = async () => {
      const { dictUrl, dictCode } = props;

      //  若传入url则按通过url获取数据
      if (dictCode) {
        list.value = getLocalStorage()[dictCode];
      } else if (dictUrl) {
        const { data } = await postRequest(dictUrl);
        list.value = data.rows;
      }
    };

    getList();

    const onChange = value => {
      emit("update:model-value", value);
    };

    watch(
      () => props.opitionList,
      newVal => {
        if (newVal && newVal.length) {
          list.value = newVal;
        }
      },
      {
        deep: true,
        immediate: true
      }
    );

    watch(
      () => props.modelValue,
      newVal => {
        if (props.multiple) {
          if (JSON.stringify(newVal) != JSON.stringify(selectValue.value)) {
            selectValue.value = [...newVal];
          }
          return;
        }
        if (newVal != selectValue.value) {
          selectValue.value = newVal;
        }
      }
    );

    return {
      selectValue,
      list,
      onChange
    };
  }
});
</script>
<style lang="scss"></style>
